package com.qijian.common.utils;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.qijian.common.exception.ServiceException;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 时间工具类
 *
 * @author ruoyi
 */
public class DateUtils extends DateUtil {

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
    public static String YYYY = "yyyy";
    public static String YYYYMM = "yyyy-MM";

    /**
     * 存放不同的日期模板格式的sdf的Map
     */
    private static final Map<String, ThreadLocal<SimpleDateFormat>> simpleDateFormatMap = new HashMap<>();


    /**
     * 锁对象
     */
    private static final Object LOCK_OBJ = new Object();

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate() {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate() {
        return dateTimeNow(DatePattern.NORM_DATE_PATTERN);
    }

    public static String getDateTime() {
        return dateTimeNow(DatePattern.PURE_DATETIME_MS_PATTERN);
    }

    public static String getDateYear() {
        return dateTimeNow(YYYY);
    }

    public static String getDateYearMonth() {
        return dateTimeNow(YYYYMM);
    }

    public static String getTime() {
        return dateTimeNow(DatePattern.NORM_DATETIME_PATTERN);
    }

    public static String format(LocalDateTime date) {
        return format(date, DatePattern.NORM_DATETIME_PATTERN);
    }

    public static Date parseData(String dateStr) {
        return parse(dateStr, DatePattern.NORM_DATETIME_PATTERN);
    }

    public static Date parseYms(String dateStr) {
        return parse(dateStr, DatePattern.NORM_DATE_FORMAT);
    }

    public static String dateTimeNow() {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static String dateTimeNow(final String format) {
        return parseDateToStr(format, new Date());
    }

    public static String dateTime(final Date date) {
        return parseDateToStr(DatePattern.NORM_DATE_PATTERN, date);
    }

    public static String parseDateToStr(final String format, final Date date) {
        return new SimpleDateFormat(format).format(date);
    }

    public static Date dateTime(final String format, final String ts) {
        try {
            return new SimpleDateFormat(format).parse(ts);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static String datePath() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static String dateTime() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate() {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 字符串转换成Date格式
     *
     * @param dateStr 日期型字符串
     * @param pattern 日期格式
     * @return Data
     */
    public static Date strToDate(String dateStr, String pattern) {
        try {
            if ((dateStr == null) || (dateStr.length() == 0)) {
                return null;
            }

            if (pattern == null) {
                pattern = DatePattern.NORM_DATE_PATTERN;
            }

            SimpleDateFormat simpleDateFormat = getSimpleDateFormat(pattern);
            return simpleDateFormat.parse(dateStr);
        } catch (Exception e) {
            return null;
        }
    }


    /**
     * 字符串转换的带time的Date格式
     *
     * @param dateStr /
     * @return /
     */
    public static Date strToDateTime(String dateStr) {
        try {
            return strToDate(dateStr, DatePattern.NORM_DATE_PATTERN);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 返回一个ThreadLocal的sdf,每个线程只会new一次sdf
     *
     * @param pattern /
     * @return /
     */
    public static SimpleDateFormat getSimpleDateFormat(final String pattern) {
        ThreadLocal<SimpleDateFormat> threadLocalSimpleDateFormat = simpleDateFormatMap.get(pattern);
        // 此处的双重判断和同步是为了防止simpleDateFormatMap这个单例被多次put重复的sdf
        if (threadLocalSimpleDateFormat == null) {
            synchronized (LOCK_OBJ) {
                threadLocalSimpleDateFormat = simpleDateFormatMap.get(pattern);
                if (threadLocalSimpleDateFormat == null) {
                    // 只有Map中还没有这个pattern的sdf才会生成新的sdf并放入map
                    // 这里是关键,使用ThreadLocal<SimpleDateFormat>替代原来直接new SimpleDateFormat
                    threadLocalSimpleDateFormat = ThreadLocal.withInitial(() -> new SimpleDateFormat(pattern));
                    simpleDateFormatMap.put(pattern, threadLocalSimpleDateFormat);
                }
            }
        }
        return threadLocalSimpleDateFormat.get();
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }


    /**
     * 计算两个时间差-分钟
     */
    public static int getDatePoorTime(Date endDate, Date nowDate, TimeUnit type) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        if (TimeUnit.DAYS == type) {
            return (int) (diff / nd);
        } else if (TimeUnit.HOURS == type) {
            return (int) (diff / nh);
        } else if (TimeUnit.MINUTES == type) {
            return (int) (diff / nm);
        } else if (TimeUnit.SECONDS == type) {
            return (int) (diff / 1000);
        }
        return 0;
    }

    /**
     * 计算两个时间差
     */
    public static long getDatePoorDay(Date endDate, Date nowDate) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day;
    }

    /**
     * 根据月份获取月份的开始时间结束时间
     *
     * @param startYearMonth 年月
     * @param json           日期范围
     * @return /
     */
    public static Map<String, Object> calEvalTime(String startYearMonth, String json) {
        Map<String, Object> map = new HashMap<>();
        //判断年月日是否包含时分秒，如果包含则去除
        if (startYearMonth.contains(":")) {
            startYearMonth = startYearMonth.substring(0, startYearMonth.indexOf(" "));
        }

        // 获取当前月
//        int nowYear = LocalDate.now().getYear();
//        int nowMonth = LocalDate.now().getMonthValue();
//        int nowDay = LocalDate.now().getDayOfMonth();
        JSONObject jsonObject = JSONUtil.parseObj(json);
        // 分割年月
        String[] yearMonthStr = startYearMonth.split("-");
        if (yearMonthStr.length == 2) {
            //只传了年月
            yearMonthStr = Arrays.copyOf(yearMonthStr, 3);
            yearMonthStr[2] = jsonObject.getStr("end");
        }
        Integer[] yearMonthInt = new Integer[]{Integer.parseInt(yearMonthStr[0]), Integer.parseInt(yearMonthStr[1]), Integer.parseInt(yearMonthStr[2])};
        // 日期限制范围
        int startYear = yearMonthInt[0], endYear = yearMonthInt[0],
                startMonth = yearMonthInt[1], endMonth = yearMonthInt[1];
        int nowDay = yearMonthInt[2];
        // 计算日期范围
        LocalDateTime start;
        LocalDateTime last;
        if (jsonObject.getBool("isMonth")) {
            LocalDate date = LocalDate.of(yearMonthInt[0], startMonth, 1);
//            if (nowDay >= jsonObject.getInt("start")) {
            if (LocalDate.of(yearMonthInt[0], yearMonthInt[1], yearMonthInt[2]).isBefore(
                    LocalDate.of(yearMonthInt[0], yearMonthInt[1], jsonObject.getInt("start")))) {
                date = date.plusMonths(-1);
                startMonth = date.getMonthValue();
                startYear = date.getYear();
            } else {
                date = date.plusMonths(1);
                endMonth = date.getMonthValue();
                endYear = date.getYear();
            }
            start = LocalDateTime.of(startYear, startMonth, jsonObject.getInt("start"), 0, 0, 0);
            last = LocalDateTime.of(endYear, endMonth, jsonObject.getInt("end"), 23, 59, 59);
        } else {
            start = LocalDateTime.of(startYear, startMonth, 1, 0, 0, 0);
            last = start.with(TemporalAdjusters.lastDayOfMonth())
                    .withHour(23)
                    .withMinute(59)
                    .withSecond(59);
        }
        map.put("beginTime", format(start, DatePattern.NORM_DATETIME_PATTERN));
        map.put("endTime", format(last, DatePattern.NORM_DATETIME_PATTERN));
        return map;
    }

    /**
     * 根据时间，计算属于哪个周期内
     *
     * @param date
     * @param json
     * @return
     */
    public static String calEvalYearMonth(LocalDate date, String json) {
        JSONObject jsonObject = JSONUtil.parseObj(json);
        if (jsonObject.getBool("isMonth")) {
            LocalDate tempDate = LocalDate.of(date.getYear(), date.getMonthValue(), jsonObject.getInt("end"));
            if (date.isAfter(tempDate))
                return LocalDateTimeUtil.format(date.plusMonths(1L), "yyyy-MM");
        }
        return LocalDateTimeUtil.format(date, "yyyy-MM");

    }

    /**
     * 获取所有月份
     */
    public static List<String> getMonth(String year) {
        List<String> result = new ArrayList<>();
        for (int i = 1; i < 13; i++) {
            result.add(String.format("%s-%02d", year, i));
        }
        return result;
    }

    /**
     * 获取每月天数
     */
    public static Map<String, Integer> getNextMonthsDays(int months) {
        Map<String, Integer> result = new LinkedHashMap<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(DateUtils.getNowDate());
        for (int i = 0; i < months; i++) {
            if (i > 0) {
                calendar.add(Calendar.MONTH, 1);
            }
            result.put(DateUtil.format(calendar.getTime(), "yyyy-MM"), calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        }
        return result;
    }

    /**
     * 月日不足2位，补足
     *
     * @param date        字符串日期
     * @param datePattern 格式
     * @return /
     */
    public static String formatStringDate(String date, String datePattern) {
        if (DatePattern.NORM_MONTH_PATTERN.equals(datePattern)) {
            String[] dates = date.split("-");
            // 月份长度小于12并且月份值小于10 月份补0
            if (2 > dates[1].length() && 10 > Integer.parseInt(dates[1])) {
                dates[1] = String.format("0%s", dates[1]);
            }
            return String.format("%s-%s", dates[0], dates[1]);
        }
        return null;
    }

    /**
     * LocalDate转换成Date
     *
     * @param localDate
     * @return
     */
    public static Date localDate2Date(LocalDate localDate) {
        if (null == localDate) {
            return null;
        }
        ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());
        return Date.from(zonedDateTime.toInstant());
    }

    public static LocalDate[] getBeginAndEndDate(LocalDate localDate) {
        int year = localDate.getYear();
        int monthValue = localDate.getMonthValue();
        LocalDate[] result = new LocalDate[2];
        if (ObjectUtils.isNull(localDate)) {
            throw new ServiceException("E01:参数为空");
        }

        int day = localDate.getDayOfMonth();
        if (day <= 25) {
            result[0] = LocalDate.of(year, monthValue - 1, 26);
            result[1] = LocalDate.of(year, monthValue, 26);
            return result;

        }

        result[0] = LocalDate.of(year, monthValue, 26);
        result[1] = LocalDate.of(year, monthValue + 1, 26);
        return result;

    }

    /**
     * 获取上个月的开始时间和结束时间（26号到26号）
     *
     * @param localDate
     * @return
     */
    public static LocalDate[] getLiatPeriodDates(LocalDate localDate) {
        int year = localDate.getYear();
        int monthValue = localDate.getMonthValue();
        LocalDate[] result = new LocalDate[2];
        if (ObjectUtils.isNull(localDate)) {
            throw new ServiceException("E01:参数为空");
        }

        int day = localDate.getDayOfMonth();
        // 当月26号
        LocalDate localDate26 = LocalDate.of(year, monthValue, 26);
        if (day <= 25) {
            result[0] = localDate26.minus(2, ChronoUnit.MONTHS);
            result[1] = localDate26.minus(1, ChronoUnit.MONTHS);
            return result;

        }

        result[0] = localDate26.minus(1, ChronoUnit.MONTHS);
        result[1] = localDate26;
        return result;

    }

    /**
     * 根据年月 获取 26-25的区间
     *
     * @param ym
     * @return
     */
    public static List<String> getPeriodViaYm(String ym) {
        String endDateStr = ym + "-25";
        LocalDate localDate = LocalDate.parse(endDateStr);
        LocalDate endDate = localDate.plusMonths(-1);
        endDate = endDate.withDayOfMonth(26);

        String startDateStr = LocalDateTimeUtil.format(endDate, "yyyy-MM-dd");

        List<String> period = new ArrayList<String>();
        period.add(startDateStr);
        period.add(endDateStr);
        return period;
    }

    public static List<String> getPeriodViaYmNew(String ym) {
        String endDateStr = ym + "-25";
        LocalDate localDate = LocalDate.parse(endDateStr);
        LocalDate endDate = localDate.plusMonths(-1);
        endDate = endDate.withDayOfMonth(26);

        String startDateStr = LocalDateTimeUtil.format(endDate, "yyyy-MM");
        String endDateStrInfo = LocalDateTimeUtil.format(localDate, "yyyy-MM");

        List<String> period = new ArrayList<String>();
        period.add(startDateStr);
        period.add(endDateStrInfo);
        return period;
    }


    public static List<String> getPeriodTimeViaYm(String ym) {
        List<String> period = getPeriodViaYm(ym);
        period.set(0, period.get(0) + " 00:00:00");
        period.set(1, period.get(1) + " 23:59:59");
        return period;
    }


    public static Date addDays(Date date, int days) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.DAY_OF_MONTH, days);
        return c.getTime();
    }

    public static String getCurrentStrDate(String... patternArr) {
        String pattern = "yyyy-MM-dd";
        if (patternArr.length > 0) {
            pattern = patternArr[0];
        }
        Date now = new Date();
        return DateFormatUtils.format(now, pattern);
    }

    /**
     * 获取上个月的时间
     *
     * @param input
     * @return
     */
    public static Date getLastMonth(Date input) {

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(input);

        calendar.add(Calendar.MONTH, -1);
        Date previousMonthDate = calendar.getTime();

        return previousMonthDate;
    }

    /**
     * 获取上个月的时间
     *
     * @param input
     * @return
     */
    public static String getLastMonthStr(Date input) {

        return DateUtils.format(getLastMonth(input), DatePattern.NORM_DATE_PATTERN);
    }


    public static String[] getStartEndDateViaYM(String ym) {
        String[] dateStr = ym.split("-");
        int year = Integer.parseInt(dateStr[0]);
        int month = Integer.parseInt(dateStr[1]);

        LocalDate lastDay = YearMonth.of(year, month).atEndOfMonth();

        String startYMD = ym + "-01";
        String endYMD = lastDay.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

        return new String[]{startYMD, endYMD};
    }


    public static String getPreviousYearLastMonth(String dateString) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        dateString = dateString + "-01";
        LocalDate date = LocalDate.parse(dateString, formatter);

        // 减去一年
        Year previousYear = Year.from(date.minusYears(1));

        // 格式化为字符串返回
        return previousYear.getValue() + "-12";
    }

    /**
     * 获取上一年
     *
     * @param inputYear
     * @return
     */
    public static String getLastYear(Integer inputYear) {
        if (inputYear == null) {
            // 获取当前日期
            LocalDate now = LocalDate.now();
            // 减去一年
            LocalDate lastYear = now.minusYears(1);
            // 创建一个DateTimeFormatter来定义输出格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy");

            // 格式化上一年的日期
            return lastYear.format(formatter);
        } else {
            Year year = Year.of(inputYear);
            Year previousYear = year.minusYears(1);
            return String.valueOf(previousYear.getValue());
        }
    }


    public static Date getLastDate() {
        Calendar calendar = Calendar.getInstance();
        // 将日期减去一天
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        // 将时分秒毫秒设置为0
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        // 从Calendar实例获取Date对象
        return calendar.getTime();
    }

    public static Date getLastDate(String inputYM) {

        if (StringUtils.isNotEmpty(inputYM)) {
            String performanceYm = getPerformanceYM();

            LocalDate currentDate = LocalDate.now();
            YearMonth inputYearMonth = YearMonth.parse(inputYM);

            YearMonth BYearMonth = YearMonth.parse(performanceYm);
            if (inputYM.equals(performanceYm) && !(currentDate.getDayOfMonth() == 1)) {
                // 如果查询日期等于绩效年月 并且当前日期不是1号，则返回当前日期减1天
                return Date.from(currentDate.minusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant());
            } else if (inputYearMonth.isAfter(BYearMonth)) {
                // 如果查询日期大于绩效年月，则返回input月份的第一天
                return Date.from(inputYearMonth.atDay(1).atStartOfDay(ZoneId.systemDefault()).toInstant());
            } else {
                // 如果查询日期小于绩效年月，则返回查询日期月份的最后一天
                return Date.from(inputYearMonth.atEndOfMonth().atStartOfDay(ZoneId.systemDefault()).toInstant());
            }
        } else return getLastDate();
    }


    public static String getLastDateStr() {
        Calendar calendar = Calendar.getInstance();
        // 将日期减去一天
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        // 将时分秒毫秒设置为0
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        // 从Calendar实例获取Date对象
        return sdf.format(calendar.getTime());
    }

    /**
     * 根据日期获取考核年月
     *
     * @return
     */
    public static String getPerformanceYM() {
        LocalDate today = LocalDate.now(); // 获取当前日期
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");

        int dayOfMonth = today.getDayOfMonth(); // 获取当前日期的几号
        // 如果今天是1号那么计算上个月的数据
        if (dayOfMonth < 2) {
            // 计算下一个月的日期
            LocalDate nextMonth = today.plusMonths(-1);
            // 检查是否是12月，如果是，则下一个月是1月
            return nextMonth.format(formatter);
        } else {
            return today.format(formatter);
        }
    }

    public static String getLastPerformanceDateStr(String inputYM) {

        String performanceYm = getPerformanceYM();

        LocalDate currentDate = LocalDate.now();
        YearMonth inputYearMonth = YearMonth.parse(inputYM);

        YearMonth BYearMonth = YearMonth.parse(performanceYm);
        if (inputYM.equals(performanceYm) && !(currentDate.getDayOfMonth() == 1)) {
            // 如果查询日期等于绩效年月 并且当前日期不是1号，则返回当前日期减1天
            return currentDate.minusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        } else if (inputYearMonth.isAfter(BYearMonth)) {
            // 如果查询日期大于绩效年月，则返回input月份的第一天
            return inputYearMonth.atDay(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        } else {
            // 如果查询日期小于绩效年月，则返回查询日期月份的最后一天
            return inputYearMonth.atEndOfMonth().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        }
    }


    /**
     * 根据当前日期 获取计算的 ymd 区间
     *
     * @param isRegularYM 是否正常年月
     * @return
     */
    public static List<String> getPerformanceYMD(Boolean isRegularYM) {
        List<String> period = new ArrayList<String>();
        // 创建日期格式化器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String startYMD;
        String endYMD;

        String ym = getPerformanceYM();

        // 解析年份和月份
        int year = Integer.parseInt(ym.split("-")[0]);
        int month = Integer.parseInt(ym.split("-")[1]);

        if (isRegularYM) {
            startYMD = ym + "-01";
            // 获取当月最后一天
            LocalDate lastDayOfMonth = YearMonth.of(year, month).atEndOfMonth();
            endYMD = lastDayOfMonth.format(formatter);
        } else {
            endYMD = ym + "-26";
            LocalDate lastMonth = LocalDate.of(year, month, 1).minusMonths(1);
            LocalDate lastMonth25th = lastMonth.withDayOfMonth(25);
            startYMD = lastMonth25th.format(formatter);
        }

        period.add(startYMD);
        period.add(endYMD);
        return period;
    }

    /**
     * 根据年月获取 evalDate
     * 当前年月取昨天，历史年月取历史年月最后一天
     *
     * @param ym
     * @return
     */
    public static String getEvalDate(String ym) {
        // 创建日期格式化器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 解析年份和月份
        int year = Integer.parseInt(ym.split("-")[0]);
        int month = Integer.parseInt(ym.split("-")[1]);
        LocalDate now = LocalDate.now();
        if (ObjectUtils.equals(year, now.getYear()) && ObjectUtils.equals(month, now.getMonthValue())) {
            return getLastDateStr();
        } else {
            LocalDate lastDayOfMonth = YearMonth.of(year, month).atEndOfMonth();
            return lastDayOfMonth.format(formatter);
        }
    }

    /**
     * 根据年月获取 绩效 evaldaily中日期的数据
     *
     * @param inputYM
     * @return
     */
    public static String getPerformanceEvalDate(String inputYM) {
        if (inputYM == null || getPerformanceYM().equals(inputYM)) {
            return getLastDateStr();
        } else {

            LocalDate date = LocalDate.parse(inputYM + "-01");
            YearMonth yearMonth = YearMonth.from(date);
            LocalDate lastDayOfMonth = yearMonth.atEndOfMonth();
            return lastDayOfMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        }
    }


    public static boolean isCurrent(String onlineYM, String checkYM) {
        String[] partsA = onlineYM.split("-");
        String[] partsB = checkYM.split("-");

        int yearA = Integer.parseInt(partsA[0]);
        int monthA = Integer.parseInt(partsA[1]);
        int yearB = Integer.parseInt(partsB[0]);
        int monthB = Integer.parseInt(partsB[1]);

        if (yearA < yearB) {
            return true;
        } else if (yearA > yearB) {
            return false;
        } else {
            if (monthA == monthB) {
                return true;
            }
            return monthA < monthB;
        }
    }

    public boolean isBeforeCurrentMonth(String ym) {
        // 解析输入的年月字符串
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
        YearMonth inputYearMonth = YearMonth.parse(ym, formatter);

        // 获取当前年月
        YearMonth currentYearMonth = YearMonth.now();

        // 比较年月
        return inputYearMonth.isBefore(currentYearMonth);
    }


    public static String checkDate(String inputYearMonth) {
        // 解析输入的年月字符串
        LocalDate inputDate = LocalDate.parse(inputYearMonth + "-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"));

        // 获取当前日期
        LocalDate currentDate = LocalDate.now();

        // 比较年月日是否相等
        if (currentDate.getDayOfMonth() == 1 && currentDate.isEqual(inputDate)) {
            // 如果相等，返回当前日期的字符串格式
            return currentDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        } else {
            // 否则返回空字符串
            return null;
        }
    }

    /**
     * 增加 LocalDateTime ==> Date
     */
    public static Date toDate(LocalDateTime temporalAccessor)
    {
        ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 增加 LocalDate ==> Date
     */
    public static Date toDate(LocalDate temporalAccessor)
    {
        LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
        ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

}
